<script setup lang="ts">
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElInput,
  ElInputNumber,
  TableColumnCtx
} from 'element-plus'
import 'element-plus/es/components/icon/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/tag/style/css'
import 'element-plus/es/components/menu/style/css'
import 'element-plus/es/components/menu-item/style/css'
import { PropType, reactive, ref, watch, h, onMounted } from 'vue'
import { useTableDialogStore } from '@/store/modules/orderTableDialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { getDiscountApi } from '@/api/product'
import Decimal from 'decimal.js'

const { formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

type tableDataType = {
  id: number
  product_name: string
  unit: string
  num: number
  unit_price: number
  unit_sum: number
  sales_price: number
  notes: string
  warehouse_name: string
  qty: number
  is_futures_value: string
  actual_price: number
  productid: number
  is_futures: number
  sku: string
}

interface SummaryMethodProps<T = tableDataType> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

const props = defineProps({
  tableDialogStoreID: {
    type: String,
    default: ''
  },
  tableDialogCurdSchema: {
    type: Array as PropType<CrudSchema[]>, // 明确类型为 CrudSchema[]
    default: () => [] // 设置默认值为一个空数组
  },
  modelValue: {
    type: Array as PropType<tableDataType[]>,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: () => false
  }
  // warehouseList: {
  //   type: Array,
  //   default: () => []
  // }
})

// 挂载完成时触发
onMounted(() => {
  // console.log(props.modelValue, 77777)
  tableData.value = props.modelValue
  // console.log(props.modelValue, 888)
})

const emit = defineEmits(['update:modelValue'])

const tableDialogStore = useTableDialogStore(props.tableDialogStoreID)
const { allSchemas } = useCrudSchemas(
  props.tableDialogCurdSchema ? props.tableDialogCurdSchema : []
)
const tableData = ref<tableDataType[]>([])

const addEmptyRow = () => {
  tableDialogStore.selectedItems = []
  tableDialogStore.openDialog()
  tableDialogStore.setSchema(allSchemas)
}

const rowClassName = ({ row }) => (row.editing ? 'editing-row' : '')
const editCell = (row) => {
  row.editing = true
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    formData.pid = tableDialogStore.selectedItems.map((item) => item.id).join(',')
    return formData
  }
}
const removeRow = (row, index) => {
  // tableDialogStore.selectedItems = tableDialogStore.selectedItems.filter(
  //   (item: SelectedItem) => item.id !== row.id
  // )
  tableDialogStore.removeItem(row.id)
  tableData.value.splice(index, 1)
}

defineExpose({
  submit
})

const discountList = ref([])

const getDiscountList = async (inventory_ids: number[]) => {
  const res = await getDiscountApi({ ids: inventory_ids })
  if (res) {
    discountList.value = res.data
  }
}

tableDialogStore.dialogSubmit = async () => {
  const existingIds = new Set(tableData.value.map((item) => item.id))
  tableDialogStore.selectionRow.forEach((item) => {
    if (!existingIds.has(item.id)) {
      tableData.value.push({
        id: item.id,
        product_name: item.product_name,
        unit: '件',
        num: 0,
        unit_price: item.sales_price,
        unit_sum: 0,
        sales_price: item.sales_price,
        notes: '',
        warehouse_name: item.warehouse_name,
        qty: item.qty,
        is_futures_value: item.is_futures_value,
        actual_price: item.actual_price,
        productid: item.productid,
        is_futures: item.is_futures,
        sku: item.sku
      })
    }
  })
  const inventory_ids = tableData.value.map((item) => item.id)

  // 这里获取折扣接口
  await getDiscountList(inventory_ids)
}
const unitSums = reactive({})
const isDisabled = ref(props.disabled)

const getSummaries = (param: SummaryMethodProps) => {
  const needHandleColumns = ['num', 'actual_price', 'unit_sum', 'id']
  const needShowMoney = ['actual_price', 'unit_sum']
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index.toString()] = h('div', { style: { textDecoration: 'underline' } }, ['Total Cost'])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (
      !values.every((value) => Number.isNaN(value)) &&
      needHandleColumns.includes(column.property)
    ) {
      sums[index] = `${needShowMoney.includes(column.property) ? '¥' : ''} ${values.reduce(
        (prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        },
        0
      )}`
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}

const changeNum = (val: number, row: Record<string, any>, index: number) => {
  if (row.actual_price) {
    let price = row.actual_price
    if (row.id in discountList.value) {
      const priceLevels = discountList.value[row.id]
      const keys = Object.keys(priceLevels)
        .map(Number)
        .sort((a, b) => a - b)
      let selectedPrice = price

      // 根据 row.num 的值选择价格区间
      for (let i = 0; i < keys.length; i++) {
        if (row.num >= keys[i]) {
          selectedPrice = parseFloat(priceLevels[keys[i].toString()])
        } else {
          break
        }
      }

      price = selectedPrice
    }
    tableData.value[index].actual_price = price
    tableData.value[index].unit_sum = new Decimal(price).mul(val).toNumber()
  }
}

watch(
  tableData,
  (newTableData) => {
    // 清空 unitSums
    Object.keys(unitSums).forEach((key) => delete unitSums[key])

    // 更新 unitSums
    // newTableData.forEach((row, index) => {
    //   unitSums[index] = row.num * row.actual_price
    //
    //   let price = row.actual_price
    //   console.log(discountList.value, 123)
    //   if (row.id in discountList.value) {
    //     const priceLevels = discountList[row.id]
    //     let selectedPrice = price
    //
    //     // 遍历 priceLevels 的键，找到合适的价格
    //     for (const level in priceLevels) {
    //       if (row.num <= parseInt(level)) {
    //         selectedPrice = parseFloat(priceLevels[level])
    //         break
    //       }
    //     }
    //
    //     price = selectedPrice
    //   }
    //   row.actual_price = price
    //   row.unit_sum = row.num * price
    // })
    // 更新表单数据
    emit('update:modelValue', newTableData)
  },
  { deep: true }
)

watch(
  () => props.modelValue,
  (val: any) => {
    console.log(val, 888)
    tableData.value = val
  }
)
</script>

<template>
  <div>
    <el-button type="primary" :disabled="isDisabled" @click="addEmptyRow">添加</el-button>
    <el-table
      :data="tableData"
      border
      show-summary
      :summary-method="getSummaries"
      style="width: 100%; margin-top: 10px"
      :row-class-name="rowClassName"
      @cell-click="editCell"
    >
      <el-table-column prop="product_name" label="产品名称">
        <template #default="{ row }">
          <span>{{ row.product_name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="warehouse_name" label="仓库名称">
        <template #default="{ row }">
          <span>{{ row.warehouse_name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="qty" label="商品库存">
        <template #default="{ row }">
          <span>{{ row.qty }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="is_futures_value" label="属性">
        <template #default="{ row }">
          <span>{{ row.is_futures_value }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="数量">
        <template #default="{ row, $index }">
          <ElInputNumber
            @change="(e: number) => changeNum(e, row, $index)"
            :disabled="isDisabled"
            v-model="row.num"
            :min="1"
            :max="row.qty"
            type="number"
          />
        </template>
      </el-table-column>
      <el-table-column prop="unit_price" label="原价">
        <template #default="{ row }">
          <span>{{ row.sales_price }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="actual_price" label="销售价">
        <template #default="{ row }">
          <el-input v-model="row.actual_price" />
        </template>
      </el-table-column>
      <el-table-column prop="unit_sum" label="单价小计">
        <template #default="{ row }">
          <el-input disabled v-model="row.unit_sum" />
        </template>
      </el-table-column>
      <el-table-column prop="notes" label="备注">
        <template #default="{ row }">
          <el-input :disabled="isDisabled" v-model="row.notes" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template #default="scope">
          <ElButton
            class="input-button"
            size="small"
            type="primary"
            plain
            link
            :disabled="isDisabled"
            @click.prevent="removeRow(scope.row, scope.$index)"
          >
            删除
          </ElButton>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.editing-row {
  background-color: #f5f7fa;
}
</style>
